package com.cashmama.market.api.application.controller.authentication.advanceAi;

import com.cashmama.market.api.application.controller.authentication.AuthenticationBaseHandler;
import com.cashmama.market.api.application.controller.authentication.AuthenticationController;
import com.cashmama.market.api.application.controller.authentication.personalInfo.InputContent;
import com.cashmama.market.api.application.controller.authentication.response.UserProfileResponse;
import com.cashmama.market.api.application.controller.authentication.vos.AuthenticationContentVo;
import com.cashmama.market.api.application.controller.authentication.vos.InputParams;
import com.cashmama.market.api.application.enums.AuthenticationTypeEnum;
import com.cashmama.market.api.application.enums.ButtonTextEnum;
import com.cashmama.market.api.application.enums.ParamType;
import com.cashmama.market.api.domain.integration.AdvanceAiIntegrationService;
import com.cashmama.market.api.domain.service.ApiUserCenterService;
import com.cashmama.market.api.domain.service.ApiUserService;
import com.cashmama.market.api.domain.vo.RequestLocalInfo;
import com.cashmama.market.api.infras.config.ApolloConfigUtil;
import com.cashmama.market.api.infras.consts.RedisKeyConsts;
import com.cashmama.market.api.infras.consts.TimeConsts;
import com.cashmama.market.api.infras.enums.JumpRouterEnum;
import com.cashmama.market.api.infras.enums.product.BottomMenuEnum;
import com.cashmama.market.api.infras.exception.ApplicationException;
import com.cashmama.market.api.infras.utils.StringUtils;
import com.fqgj.base.services.redis.RedisClient;
import com.fqgj.common.api.Response;
import com.fqgj.exception.common.ApiErrorException;
import com.fqgj.xjd.user.client.UserAadhaarService;
import com.fqgj.xjd.user.client.UserKycDocumentService;
import com.fqgj.xjd.user.client.request.UserAdvanceAadhaarVo;
import com.fqgj.xjd.user.client.response.UserKycDocumentInfo;
import com.qianli.user.enums.UserAuthEnum;
import com.qianli.user.enums.UserAuthStatusEnum;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: yujianfu (mr.vencnet@gmail.com)
 * Date: 2019-12-20
 * Time: 16:33
 */
@Service
public class AdvanceAiAuthenticationHandler extends AuthenticationBaseHandler {
    private final static Logger LOGGER = LoggerFactory.getLogger(AdvanceAiAuthenticationHandler.class);

    @Autowired
    private ApolloConfigUtil apolloConfigUtil;

    @Autowired
    private ApiUserCenterService apiUserCenterService;

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private AdvanceAiIntegrationService advanceAiIntegrationService;

    @Autowired
    private UserAadhaarService userAadhaarService;

    @Autowired
    private UserKycDocumentService userKycDocumentService;
    @Autowired
    private ApiUserService apiUserService;


    @PostConstruct
    public void init() {
        AuthenticationController.authenticationBaseHandlerMap.put(AuthenticationTypeEnum.ADVANCE_AI.getType(), this);
    }

    @Override
    public UserProfileResponse save(Map<String, String> inputParams) {
        String jumpUrl = BottomMenuEnum.HOME.getJumpUrl();
        AdvanceAi advanceAi = new AdvanceAi();
        getObject(advanceAi, inputParams);

        //保存逻辑
        String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
        Boolean complete = apiUserCenterService.advanceAadhaarActionComplete(userCode);
        UserProfileResponse userProfileResponse = new UserProfileResponse();
        if (complete) {
            LOGGER.info("advanceAi已认证,略过1,userCode:{}", userCode);
            userProfileResponse.setJumpUrl(jumpUrl);
            return userProfileResponse;
        }

        InputParams aadhaarNo = advanceAi.getCardNo();
        if (StringUtils.isEmpty(aadhaarNo.getInputValue())) {
            throw new ApiErrorException("Aadhaar number cannot be empty");
        }

        String data = "test";
        if (!apolloConfigUtil.isServerTest()) {
            String transactionId = redisClient.get(RedisKeyConsts.ADVANCEAI_TRANSACTIONID_KEY, userCode, aadhaarNo.getInputValue());
            if (transactionId == null) {
                throw new ApplicationException("Please try again");
            }
            String otp = advanceAi.getAadhaarAiOtp().getInputValue();

            String message = redisClient.get(RedisKeyConsts.ADVANCEAI_CACHA_RESULT_KEY, transactionId, otp);
            if (StringUtils.isNotEmpty(message)) {
                LOGGER.info("重复请求拦截,userCode:{},transactionId:{},otp:{},msg:{}", userCode, transactionId, otp, message);
                throw new ApplicationException(message);
            }
            try {
                data = advanceAiIntegrationService.identityCheckResult(userCode, transactionId, otp);
            } catch (ApplicationException e) {
                String msg = StringUtils.isEmpty(e.getMessage()) ? "Failed." : e.getMessage();
                redisClient.set(RedisKeyConsts.ADVANCEAI_CACHA_RESULT_KEY, msg, TimeConsts.ONE_MINUTE, transactionId, otp);
                LOGGER.warn("advanceAi验证失败,userCode:{},transactionId:{},otp:{},msg:{}", userCode, transactionId, otp, msg);
                throw e;
            }
        }

        UserAdvanceAadhaarVo userAdvanceAadhaarVo = new UserAdvanceAadhaarVo();
        userAdvanceAadhaarVo.setUserCode(userCode);
        userAdvanceAadhaarVo.setAadhaarNo(aadhaarNo.getInputValue());
        userAdvanceAadhaarVo.setStatus(2);
        userAdvanceAadhaarVo.setResult(data);
        userAadhaarService.addUserAdvanceAadhaar(userAdvanceAadhaarVo);
        apiUserService.updateUserAuthStatus(UserAuthStatusEnum.SUCCESS, UserAuthEnum.ADVANCE_STATUS, RequestLocalInfo.getCurrentUser().getUserCode());
        Response<List<UserKycDocumentInfo>> kycInfoResponse = userKycDocumentService.getByUserCode(userCode);
        if (!kycInfoResponse.isSuccess()) {
            throw new ApplicationException(kycInfoResponse.getCode(), kycInfoResponse.getMsg());
        }

        if (kycInfoResponse.getData() == null || CollectionUtils.isEmpty(kycInfoResponse.getData())) {
            jumpUrl = JumpRouterEnum.ACTION_PROFILE.getJumpUrl();
        }
        userProfileResponse.setJumpUrl(jumpUrl);
        return userProfileResponse;
    }

    @Override
    public AuthenticationContentVo content() {
        AuthenticationContentVo authenticationContentVo = explain(new AdvanceAi());
        authenticationContentVo.setButtonText(ButtonTextEnum.NEXT.getText());
        authenticationContentVo.setButtonVisibility(true);
        return authenticationContentVo;
    }


    public class AdvanceAi {
        @InputContent(param = "cardNo", paramType = ParamType.GET_OTP, burialPointName = "aadhaar_check_otp", inputDesc = "Input Aadhaar Number")
        private InputParams cardNo;

        @InputContent(param = "aadhaarAiOtp", paramType = ParamType.INPUT_NO_TITLE, inputDesc = "Enter OTP")
        private InputParams aadhaarAiOtp;


        public InputParams getCardNo() {
            return cardNo;
        }

        public AdvanceAi setCardNo(InputParams cardNo) {
            this.cardNo = cardNo;
            return this;
        }

        public InputParams getAadhaarAiOtp() {
            return aadhaarAiOtp;
        }

        public AdvanceAi setAadhaarAiOtp(InputParams aadhaarAiOtp) {
            this.aadhaarAiOtp = aadhaarAiOtp;
            return this;
        }


    }
}
